import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:http/http.dart' as http;
import 'package:psi/entity/response/oss_sts_resp.dart';
import 'package:psi/http/api_service.dart';
import 'package:psi/http/http.dart';
import 'package:psi/utils/utils.dart';
import 'package:uuid/uuid.dart';

class OssUtil {
  factory OssUtil() => _getInstance();


  static OssUtil get instance => _getInstance();
  static late OssUtil _instance;

  static OssUtil _getInstance() {
    _instance = OssUtil._internal();
    return _instance;
  }

  OssUtil._internal() {
    print('初始化OSS');
    // 初始化OSSClient
    Client.init(
        ossEndpoint: 'oss-cn-nanjing.aliyuncs.com',
        bucketName: 'psi-img',
        authGetter: getSTSAuth
    );
  }

  static Future<Auth> getSTSAuth() async {
    try {
      OssStsResp ossSts = await ApiService.request.ossSts();
      if (ossSts.code != 0) {
        return Auth(accessKey: "", accessSecret: "", secureToken: "", expire: "");
      }
      STSData sts = ossSts.data!;
      Auth auth = Auth(accessKey: sts.accessKeyId!, accessSecret: sts.accessKeySecret!, secureToken: sts.securityToken!, expire: sts.expiration!);
      return auth;
    } catch (e) {
      Utils.logE("获取sts授权失败：", error: e);
      return Auth(accessKey: "", accessSecret: "", secureToken: "", expire: "");
    }

  }

  static Future<String?> uploadFile(String imagePath, {bool showLoading = true}) async {
    if (showLoading) {
      Utils.showLoading();
    }
    try {
      List<int> bytes = [];
      String fileName;
      if (kIsWeb) {
        final response = await http.get(Uri.parse(imagePath));
        if (response.statusCode == 200) {
          var header = response.headers['content-type'];
          bytes = response.bodyBytes;
          fileName = Uuid().v1() + "." + header!.split("/").last;
        } else {
          return null;
        }
      } else {
        File file = File(imagePath);
        bytes = file.readAsBytesSync();
        fileName = Uuid().v1() + "." + imagePath.split("/").last;
      }
      if (bytes.isEmpty) {
        return null;
      }

      var response = await Client().putObject(
        bytes,
        fileName,
        option: PutRequestOption(
          onSendProgress: (count, total) {
            print("send: count = $count, and total = $total");
          },
          onReceiveProgress: (count, total) {
            print("receive: count = $count, and total = $total");
          },
          override: false,
          aclModel: AclMode.publicRead,
          storageType: StorageType.ia,
          headers: {"cache-control": "no-cache"},
          callback: Callback(
            callbackUrl: "callback url",
            callbackBody: "{\"mimeType\":\${mimeType}, \"filepath\":\${object},\"size\":\${size},\"bucket\":\${bucket},\"phone\":\${x:phone}}",
            callbackVar: {"x:phone": "android"},
            calbackBodyType: CalbackBodyType.json,
          ),
        ),
      );
      if (showLoading) {
        Utils.hideLoading();
      }
      if (response.statusCode == 200) {
        Utils.logI("oss 上传成功：${response.requestOptions.path}");
        return response.requestOptions.path;
      } else {
        Utils.showToast("图片上传失败");
        return null;
      }

    } catch (e) {
      if (showLoading) {
        Utils.hideLoading();
      }
      Utils.showToast("图片上传失败");
      return null;
    }
  }
}
